#define _CRT_SECURE_NO_WARNINGS 1

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int minDepth(TreeNode* root)
    {
        if (root == nullptr)
            return 0;
        int depth = INT_MAX;
        return _minDepth(root, 0, depth);
    }

private:
    int _minDepth(TreeNode* root, int high, int& depth)
    {
        if (root->left == nullptr && root->right == nullptr)
        {
            return 1;
        }

        int left = INT_MAX - 1;
        if (root->left != nullptr)
        {
            left = _minDepth(root->left, high + 1, depth);
            depth = std::min(depth, high + left);
        }

        int right = INT_MAX - 1;
        if (root->right != nullptr)
        {
            right = _minDepth(root->right, high + 1, depth);
            depth = std::min(depth, high + right);
        }

        return 1 + std::min(left, right);
    }
};